<template>
  <x-form ref="formRef" v-model:model="file" :rules="rules" label-placement="top" label-width="120">
    <n-form-item path="media_url" label='头像' :ignore-path-change="true">
      <div class="flex-1">
        <div class="upfile-container" @click="openUpFile">
          <div class="creative-upfile-info" v-if="!file.media_url">
            <div class="creative-upfile-specs">
              (要求尺寸: {{ upRules.rect[0] }}px × {{ upRules.rect[1] }}px )
            </div>
            <div class="creative-upfile-text">点击上传</div>
            <div class="creative-upfile-tip">
              <span>{{ rulesTips }}</span>
            </div>
          </div>
          <input type="file" hidden ref="uploadRef" :accept="accept" @change="beforeUpload" />
          <div class="creative-upfile-display" v-if="file.media_url">
            <f-media class="flex center" :media_url="file.media_url" :meta_type="file.meta_type"
              :loading="file.loading"> </f-media>
          </div>
        </div>
      </div>
    </n-form-item>
    <n-form-item label="品牌名称" path="text">
      <n-input v-model:value="file.text" :accept="accept" :maxlength="12" :show-count="true" :count-graphemes="count"></n-input>
    </n-form-item>
  </x-form>

</template>
<script setup lang="ts">
import { reactive, computed, ref, toRef } from 'vue';
import { useStore } from '@/store';
import { XForm } from '@/components';
import { NInput, NFormItem } from 'naive-ui';
import FMedia from './f-media.vue';
import { useUpload } from '../hooks/useUpload';
import http from '@/utils/http/axios';
import { count } from '@/utils/text';
const store = useStore();
const account = computed(() => {
  const accounts = store.state.adv.accounts;
  return accounts[0];
})

const props = defineProps({
  rules: {

  }
})
const file: any = ref({
  id: Date.now(),
  media_url: '',
  meta_type: 'image',
  loading: false,
  file: null,
  text: '',

})
const upRules = toRef<any, string>(props, 'rules');
// const upRules = computed(() => {
//   return {
//     rect: [512, 512],
//     suggest: [512, 512],
//     // kb
//     size: 40,
//     ratio: [],
//     duration: [],
//     file_format: ['JPG', 'PNG'],
//   }
// })
const { validate, accept, rulesTips } = useUpload({
  rules: upRules
})
const uploadRef = ref();
const rules = reactive({
  text: {
    type: 'string',
    required: true,
    trigger: ['change'],
    message: '请输入品牌名称'
  },
  media_url: {
    type: 'string',
    required: true,
    trigger: ['change'],
    message: '请上传图片'
  }
})

function openUpFile() {
  uploadRef.value.value = '';
  uploadRef.value.click();
}

function getImageUrl(file: any): Promise<string> {
  return new Promise((r, j) => {
    const fileRead = new FileReader();
    fileRead.readAsDataURL(file.file);
    fileRead.onload = function () {
      r(this.result as string)
    }
    fileRead.onerror = function () {
      j('');
    }
  })

}

async function beforeUpload(e: any) {
  const text = file.value.text;

  file.value = {
    loading: false,
    file: e.target.files[0],
    id: Date.now(),
    media_url: '',
    meta_type: 'image',
    text
  };
  const info = await validate(file.value);

  if (!info) return;
  file.value.loading = true;
  const url = await getImageUrl(file.value);
  file.value.media_url = url;
  file.value.loading = false;
}
const formRef = ref()
function submit() {
  return new Promise((r, j) => {
    formRef.value.validate(async (err: any) => {
      if (!err) {
        const { data } = await http.uploadFiles({
          url: `/api/adgroup/brand/upload`,
          method: 'post',
          data: {
            accountCode: account.value ? account.value.accountCode : undefined,
            fileName: file.value.text
          }
        }, file.value.file) as any;
        r(data)
      } else {
        j({})
      }
    })
  })

}

defineExpose({
  submit
})


</script>
<style lang="scss" scoped>
.upfile-container {
  height: 200px;
  background-color: #f5f6f8;
  flex: 1;
  position: relative;
  border: 1px solid #e6e8ed;
  border-radius: 4px;
  width: 200px;
}


.creative-upfile-info {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: rgba(0, 0, 0, .3);
}

.creative-upfile-info .creative-upfile-title {
  display: block;
  font-size: 22px;
  font-weight: 600
}

.creative-upfile-tip {
  margin: 10px 20px 0;
  padding: 10px 0 0;
  border-top: 1px solid #dfe1e6;
  text-align: center;
  font-size: 12px;
}

.creative-upfile-text {
  font-weight: 600;
  color: var(--gray-7)
}

.creative-upfile-display {

  position: absolute;
  height: 90%;
  max-width: 252px;
  width: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;

}
</style>
